﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using RN.ERP.Web.BasicService;
using RN.ERP.Web.ModelService;
using Newtonsoft.Json;
using System.Web.SessionState;
using Fly.Common.Linq;
using System.IO;

namespace RN.ERP.Web.Handlers
{
    /// <summary>
    /// LoginHandler 的摘要说明
    /// </summary>
    public class LoginHandler : IHttpHandler, IRequiresSessionState
    {
        private string AppID
        {
            get
            {//
                return HttpContext.Current.Application[ApplicationConstant.APPLICATION_ID].ToString();
            }
        }

        private string SysArea
        {
            get
            {
                return ConfigurationManager.AppSettings["sysArea"];
            }
        }

        private bool IsAppRightOpen
        {
            get
            {
                return ConfigurationManager.AppSettings["IsAppRightOpen"]=="true";
            }
        }

        public void ProcessRequest(HttpContext context)
        {
            string userName = context.Request["userName"] ?? string.Empty;
            string passWord = context.Request["passWord"] ?? string.Empty;
            string dogId = context.Request["dogId"] ?? string.Empty;
            string type = context.Request["type"] ?? string.Empty;
            string action = context.Request["action"] ?? string.Empty;
            string msg = null;
            if (!string.IsNullOrEmpty(action))
            {
                switch (action.ToLower())
                {
                    case "getuserinfobydogid":
                        msg = this.GetUserInfobyDogID(dogId);
                        break;
                }
            }
            else
            {
                if (!string.IsNullOrEmpty(passWord))
                {
                    BasicServiceClient client = new BasicServiceClient();
                    EnterpriseService.EnterpriseServiceClient enterpriseServiceClient = new EnterpriseService.EnterpriseServiceClient();
                    UserInfo userInfo = JsonConvert.DeserializeObject<UserInfo>(client.DoLoginWithAuthority(userName, passWord, dogId, type, string.Empty, AppID));
                    Tb_Corp_CompanyInfo corp = new Tb_Corp_CompanyInfo();
                    Guid guid = Guid.Empty;
                    Guid.TryParse(userInfo.UserGuid, out guid);
                    if (userInfo.Result)
                    {
                        SessionUserInfo sui = new SessionUserInfo();
                        sui.UserName = userInfo.UserName;
                        sui.Name = userInfo.Name;
                        sui.CorpUserGuid = userInfo.UserGuid;
                        sui.DogId = userInfo.DogId;
                        sui.RoleId = userInfo.RoleId;
                        sui.FuncPerm = userInfo.FuncPerm;
                        sui.AreaCode = userInfo.AreaCode;
                        sui.LocalArea = userInfo.AreaCode2;
                        sui.RoleType = userInfo.RoleType;
                        sui.RoleTypeTitle = userInfo.RoleTypeTitle;
                        sui.CurrentArea = string.IsNullOrEmpty(userInfo.AreaCode) ? string.Empty : userInfo.AreaCode.Substring(0, 2);

                        ////只有企业端才存在市场范围的区分，主管端不检查市场范围 2014-1-10 毛凯
                        if (sui.RoleType == "User")
                        {

                            List<Tb_Corp_Embranchment> CorpEmbranchments = new List<Tb_Corp_Embranchment>();
                            if (guid != null && guid != Guid.Empty)
                            {
                                corp.CorpUserGuid = guid;
                                var Embranchments = enterpriseServiceClient.GetCorpEmbranchments(JsonConvert.SerializeObject(corp));
                                CorpEmbranchments = JsonConvert.DeserializeObject<List<Tb_Corp_Embranchment>>(Embranchments);
                            }
                            if (CorpEmbranchments != null && CorpEmbranchments.Count > 0)
                            {
                                ////若是为本地企业则默认注册地为当前市场范围，否则则取第一个
                                var currentEmbranchment = CorpEmbranchments.Where(e => userInfo.AreaCode.StartsWith(e.AreaCode)).FirstOrDefault();
                                sui.CurrentArea = currentEmbranchment == null ? CorpEmbranchments[0].AreaCode.Substring(0, 2) : currentEmbranchment.AreaCode.Substring(0, 2);
                            }
                        }
                        string sysArea = ConfigurationManager.AppSettings["sysArea"];
                        if (!string.IsNullOrEmpty(sysArea) && sysArea != sui.CurrentArea)
                        {
                            sui.CurrentArea = sysArea;
                        }
                        HttpContext.Current.Session[SessionConstant.SESSION_USERINFO] = sui;
                        ////当前市场范围，暂时处理,外地企业则需要首次登陆时确定市场范围
                        ////用SessionUserInfo.CurrentArea替代。
                        ////HttpContext.Current.Session[SessionConstant.SESSION_CURRENT_AREACODE] = userInfo.AreaCode;

                        if (sui.RoleType == "User" && IsAppRightOpen && !IsAppRightValid(userInfo.UserGuid))
                        {
                            msg = "对不起，您没有访问该系统的权限。";
                        }
                        else
                        {
                            int appid = 0;
                            int.TryParse(System.Configuration.ConfigurationManager.AppSettings["AppID"], out appid);
                            string areaCode = System.Configuration.ConfigurationManager.AppSettings["sysArea"];
                            if ("06" == areaCode)
                            {
                                enterpriseServiceClient.GenerateFlowCodebyAppId(userInfo.UserGuid, appid, areaCode);
                            }
                            msg = "success";
                            context.Response.Cookies[CookieConstant.COOKIE_USERGUID].Value = userInfo.UserGuid.ToString();
                            List<QueryCompanyInfoCondition> listCondition = new List<QueryCompanyInfoCondition>();
                            QueryCompanyInfoCondition companyInfoQuery = new QueryCompanyInfoCondition();
                            companyInfoQuery.CorpUserGuid = new Fly.Common.Linq.ParameterValue<Guid>() { O = OptEnum.Equal, V = guid };
                            listCondition.Add(companyInfoQuery);
                            var companyInfo = JsonConvert.DeserializeObject<Tb_Corp_CompanyInfo>(enterpriseServiceClient.GetCompanyInfo(JsonConvert.SerializeObject(listCondition), sui.CurrentArea));
                            //TokenLogin(context, userInfo, companyInfo);
                        }
                    }
                    else
                    {
                        msg = userInfo.Message;
                    }
                }
                else
                {
                    msg = "登录失败！";
                }
            }
            context.Response.ContentType = "text/plain";
            context.Response.Write(msg);
        }

        private bool IsAppRightValid(string UserGuid)
        {
            BasicServiceClient client = new BasicServiceClient();
            return client.IsAppRightValid(int.Parse(AppID), Guid.Parse(UserGuid), SysArea);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        //private void TokenLogin(HttpContext context, UserInfo user, Tb_Corp_CompanyInfo corp)
        //{
        //    #region 令牌 edit by duan_yg
        //    //产生令牌
        //    string tokenValue = Guid.NewGuid().ToString().ToUpper();

        //    context.Response.Cookies.Add(new HttpCookie("LoginToken",tokenValue));
        //    HttpContext.Current.Session["token2"] = tokenValue;
        //    try
        //    {
        //        //WriteLog(string.Format("tokenValue:{0},Name:{1}", tokenValue, model.OldUser.Name));
        //        //产生主站凭证
        //        TokenService.TokenServiceSoapClient client = new TokenService.TokenServiceSoapClient();
        //        TokenService.DistriLogin userinfo = new TokenService.DistriLogin();
        //        userinfo.AreaCode = user.AreaCode;
        //        userinfo.RealAreaCode = "";
        //        userinfo.bGrade =string.IsNullOrEmpty(user.RoleId)?-1:int.Parse(user.RoleId);
        //        userinfo.ClassId = corp.classID;
        //        userinfo.CorpGuid = corp.CorpGuid;
        //        userinfo.isAdmin = user.RoleType!="User";
        //        userinfo.Name = user.Name;
        //        Guid userGuid = Guid.Empty;
        //        Guid.TryParse(user.UserGuid,out userGuid);
        //        userinfo.UserGuid = userGuid;
        //        userinfo.UserName = user.UserName;
        //        userinfo.DogId = string.IsNullOrEmpty(user.DogId)?-1:int.Parse(user.DogId);
        //        userinfo.UserID = user.UserID;
        //        userinfo.CorpID = corp.ID;
        //        client.TokenInsert(tokenValue, userinfo);
        //        //WriteLog(tokenValue + "写入缓存成功");
        //    }
        //    catch (Exception ex)
        //    {
        //        //WriteLog(string.Format("出错：tokenValue:{0},Name:{1}出错信息：{2}", tokenValue, model.OldUser.Name, ex.Message));
        //       //WriteLog(tokenValue+"写入缓存出错"+ex.Message);
        //    }

        //    #endregion
        //}

        private string GetUserInfobyDogID(string dogId)
        {
              BasicServiceClient client = new BasicServiceClient();
              string str = "{\"result\":false,\"message\":\"请插入有效的密码锁！\"}";
              try
              {
                  if (!string.IsNullOrEmpty(dogId))
                  {
                      int dog = -1;
                      int.TryParse(dogId, out dog);
                      if (dog != -1)
                      {
                          string userinfo = client.GetUserInfobyDogID(dog, ConfigurationManager.AppSettings["sysArea"]);//根据key号获取用户信息，含用户是否主管

                          UserInfo user = JsonConvert.DeserializeObject<UserInfo>(userinfo);
                          str = JsonConvert.SerializeObject(new  { ReturnValue=user.Name, Result = user.IsManager, Message = user.UserName });
                      }
                  }
              }
              catch (Exception ex)
              {

              }
                return str;
        }

      
    }
}
